package com.atguigu.spzx.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.dto.h5.UserLoginDto;
import com.atguigu.spzx.model.dto.h5.UserRegisterDto;
import com.atguigu.spzx.model.entity.user.UserInfo;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.h5.UserInfoVo;
import com.atguigu.spzx.service.exception.GuliException;
import com.atguigu.spzx.service.utils.AuthContextUtils;
import com.atguigu.spzx.user.mapper.UserInfoMapper;
import com.atguigu.spzx.user.service.UserInfoService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: UserInfoServiceImpl
 * Package: com.atguigu.spzx.user.service.impl
 * Description:
 *
 * @Author 刘强
 * @Create 2024/7/16 4:15
 * @Version 1.0
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 注册
     *
     * @param userRegisterDto
     */
    @Override
    public void register(UserRegisterDto userRegisterDto) {
        // 1. 判断信息是否为空
        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String nickName = userRegisterDto.getNickName();
        String code = userRegisterDto.getCode();
        if (username == null || password == null || nickName == null || code == null) {
            throw new GuliException(301, "注册信息不够!");
        }
        // 2. 判断验证码
        String codeRedis = stringRedisTemplate.opsForValue().get("phone:code:" + username);
        if(!code.equals(codeRedis)){
            throw new GuliException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        // 3. 判断用户名(手机号)是否已经注册
        UserInfo userInfo = userInfoMapper.findByUsername(username);
        if(userInfo != null){
            throw new GuliException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        // 4. 字段填充
        userInfo = new UserInfo();
        BeanUtils.copyProperties(userRegisterDto,userInfo);
        userInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userInfo.setPhone(username);
        userInfo.setAvatar("http://192.168.1.128:9001/spzx-bucket/20240702/30db1a28e5344bbf832d7c952e7b5e8324.jpg");
        userInfo.setSex(0);
        userInfo.setStatus(1);
        // 5. 插入数据
        userInfoMapper.save(userInfo);
    }

    /**
     * 用户登录
     * @param userLoginDto
     * @param request
     */
    @Override
    public String login(UserLoginDto userLoginDto, HttpServletRequest request) {
        String username = userLoginDto.getUsername();
        String password = userLoginDto.getPassword();
        if(StrUtil.isEmpty(username) || StrUtil.isEmpty(password)){
            throw new GuliException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 1. 根据用户名获取用户信息
        UserInfo userInfo = userInfoMapper.findByUsername(username);
        // 3. 校验账户状态
        if(userInfo.getStatus() == 0){
            throw new GuliException(ResultCodeEnum.ACCOUNT_STOP);
        }
        // 2. 校验密码
        if(!DigestUtils.md5DigestAsHex(password.getBytes()).equals(userInfo.getPassword())){
            throw new GuliException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 3. 生成token保存到redis中
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        stringRedisTemplate.opsForValue().set("user:login:"+token, JSON.toJSONString(userInfo),7, TimeUnit.DAYS);
        // 4. 更新数据库  -> 登陆的ip地址，登陆时间
        userInfoMapper.updateById(userInfo);
        // 5. 设置返回值
        return token;
    }

    /**
     *  方式二 ： 优化后
     * 获取用户信息
     * @param token
     * @return
     */
    @Override
    public UserInfoVo getCurrentUserInfo(String token) {
        UserInfo userInfo = AuthContextUtils.get();
        // 封装返回值
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setNickName(userInfo.getNickName());
        userInfoVo.setAvatar(userInfo.getAvatar());
        return userInfoVo;
    }

//    /**
//     *  方式一 ： 优化前
//     * 获取用户信息
//     * @param token
//     * @return
//     */
//    @Override
//    public UserInfoVo getCurrentUserInfo(String token) {
//        // 1. 从redis中获取用户信息
//        String userInfoStr = stringRedisTemplate.opsForValue().get("user:login:" + token);
//        // 2. 判断是否为空，如果为空则表明用户未登录
//        if(StringUtils.isEmpty(userInfoStr)){
//            throw new GuliException(ResultCodeEnum.LOGIN_AUTH);
//        }
//        // 3. 封装返回值
//        UserInfoVo userInfoVo = new UserInfoVo();
//        UserInfo userInfo = JSON.parseObject(userInfoStr, UserInfo.class);
//        userInfoVo.setNickName(userInfo.getNickName());
//        userInfoVo.setAvatar(userInfo.getAvatar());
//        return userInfoVo;
//    }
}
